package test0309;

import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 */
public class Main03 {

    public static void main(String[] args) {
        MyString myString = new MyString();
        myString.createString();
        System.out.println("该字符串的长度: " + myString.getLength());
        System.out.println("该字符串是否为空: " + myString.isEmpty());
        myString.myPrint();
        System.out.println("在 index = 2 位置 插入一个 X ");
        myString.insert(2, 'X');
        myString.myPrint();
        System.out.println("该字符串的长度: " + myString.getLength());
        System.out.println("该字符串是否为空: " + myString.isEmpty());
    }
}


@SuppressWarnings({"all"})
class MyString {

    private char[] val; // 存储字符串的值
    private int length; // 记录字符串长度

    // 返回字符串的长度
    public int getLength(){
        return length;
    }

    // 创建一个字符串
    public void createString(){
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("请输入要创建的字符串的长度: ");
            length = scanner.nextInt();
            scanner.nextLine();
            System.out.println("请输入一个字符串: ");
            val = scanner.nextLine().toCharArray();
        }
    }

    // 打印该字符串
    public void myPrint(){
        System.out.print("该字符串为: ");
        for (int i = 0; i < val.length; i++) {
            System.out.print(val[i]);
        }
        System.out.println();
    }

    // 实现字符串的插入
    public void insert(int index, char c){
        if (index < 0 || index > length){
            throw new RuntimeException("位置不合法!");
        }
        char[] newVal = new char[length + 1];
        int cur = 0;
        while (cur < index){
            newVal[cur] = val[cur];
            cur++;
        }
        newVal[index] = c;
        // 继续存储剩下的
        while (cur < val.length){
            newVal[++index] = val[cur];
            cur++;
        }
        val = newVal;
        length++;
    }

    // 字符串的判空
    public boolean isEmpty(){
        return length == 0;
    }
}
